package org.example.queue;

import javax.swing.tree.TreeNode;
import java.util.*;

/**
 * 给你二叉树的根节点 root ，返回其节点值的 锯齿形层序遍历 。（即先从左往右，再从右往左进行下一层遍历，以此类推，层与层之间交替进行）。
 * 输入：root = [3,9,20,null,null,15,7]
 * 输出：[[3],[20,9],[15,7]]
 */
public class ZigzagLevelOrder {
    public class TreeNode {
      int val;
      TreeNode left;
      TreeNode right;
     TreeNode() {}
      TreeNode(int val) { this.val = val; }
      TreeNode(int val, TreeNode left, TreeNode right) {
          this.val = val;
          this.left = left;
          this.right = right;
     }
    }
    public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
        Queue<TreeNode> queue = new LinkedList<>();
        List<List<Integer>> ret = new ArrayList<>();
        if(null == root) return ret;
        //判断这层是否逆序
        boolean isreverse = false;
        queue.add(root);
        //统计每层数量
        int count = 0;
        while(!queue.isEmpty()){
            count = queue.size();
            List<Integer> tmp = new ArrayList<>();
            while(count--!=0){
                TreeNode cur = queue.poll();
                if(cur.left!=null){
                    queue.add(cur.left);
                }
                if(cur.right!=null){
                    queue.add(cur.right);
                }
                tmp.add(cur.val);
            }
            if(isreverse){
                Collections.reverse(tmp);
            }
            isreverse=!isreverse;
            ret.add(tmp);
        }
        return ret;
    }
}
